package core.world;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import java.util.Vector;

import core.SingleButtonGame;
import core.units.Unit;

public class CollisionHandler {

	public static SingleButtonGame main;
	
	/**
	 * handles all collisions between units and obstacles
	 */
	public static void handleCollisions(){
		Vector<Wall> walls = main.map.walls;
		for(Unit u : main.units){
			if(u.isAlive())
				for(Wall w : walls){
					if(w.getOuterBounds().intersects(u.bounds))
						if(w.intersects(u.bounds))
							handleCollision(u, w);
				}
		}
		
	}
	
	public static void init(SingleButtonGame m){
		main=m;
	}
	
	public static boolean intersects(Point p1, Point p2, Rectangle rect){
		Point p3=rect.getLocation();
		Point p4=rect.getLocation();
		p4.translate(rect.width, rect.height);
		if(intersects(p1, p2, p3, p4)){
			return true;
		}
		p3.translate(rect.width, 0);
		p4.translate(-rect.width, 0);
		if(intersects(p1, p2, p3, p4)){
			return true;
		}
		
		return false;
	}
	/**
	 * Lines from p1 to p2 and p3 to p4
	 * @return
	 */
	public static boolean intersects(Point p1, Point p2, Point p3, Point p4){		
		return Line2D.linesIntersect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), p3.getX(), p3.getY(), p4.getX(), p4.getY() );
		//return false;
	}
	
	public static boolean intersects(Point p1, Point p2){
		for(Wall w : main.map.walls){
			if(w.intersects(p1, p2)){
				return true;
			}
		}
		return false;
	}
	
	
	
	public static void setMain(SingleButtonGame m){
		main = m;
	}
	
	private static void handleCollision(Unit u, Wall w){
		int force = 100;
		for(int i=100;  i!=0 && w.intersects(u.bounds); i--){
			u.pushX((int)(force*w.dx));
			u.pushY((int)(force*w.dy));
			
		}
	}
	
}
